package cn.tedu.es.repo;

import cn.tedu.es.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

@Component
public class StuSearcher {

    @Autowired
    private ElasticsearchOperations operations;

    public List<Student> findByBirthDate(String birthDate) {
        Criteria c = new Criteria("birthDate");
        c.is(birthDate);
        return search(c);
    }

    public List<Student> findByBirthDate(String from,String to) {
        Criteria c = new Criteria("birthDate");
        c.between(from,to);
        return search(c);
    }

    private List<Student> search(Criteria c) {
        CriteriaQuery q = new CriteriaQuery(c);
        SearchHits<Student> hits = operations.search(q, Student.class);

        // 集合操作
        CopyOnWriteArrayList<Student> list = new CopyOnWriteArrayList<>();
        for (SearchHit<Student> hit : hits) {
            Student content = hit.getContent();
            list.add(content);
        }

        // 集合流操作
        //List<Student> list = hits.stream().map(SearchHit::getContent).collect(Collectors.toList());

        return list;
    }

}
